using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
public class BaiduPanDownloader {
    readonly string _accessToken;
    readonly HttpClient _httpClient = new HttpClient();

    public BaiduPanDownloader(string accessToken) {
        _accessToken = accessToken;
        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_accessToken}");
    }

    // 获取文件下载链接
    async Task<string> GetDownloadUrl(string remoteFilePath) {
        var url = $"https://pan.baidu.com/rest/2.0/xpan/file?method=download&access_token={_accessToken}&path={Uri.EscapeDataString(remoteFilePath)}";
        var response = await _httpClient.GetAsync(url);
        var result = JObject.Parse(await response.Content.ReadAsStringAsync());
        return result["url"].ToString(); // 下载地址（带有效期）
    }

    // 下载文件到本地
    public async Task DownloadFile(string remoteFilePath, string localSavePath) {
        var downloadUrl = await GetDownloadUrl(remoteFilePath);

        // 下载文件内容（注意：下载链接可能需要Referer头，否则会403）
        using (var request = new HttpRequestMessage(HttpMethod.Get, downloadUrl)) {
            request.Headers.Referrer = new Uri("https://pan.baidu.com/"); // 必须添加，否则禁止访问
            using (var response = await _httpClient.SendAsync(request)) {
                response.EnsureSuccessStatusCode();
                using (var fileStream = new FileStream(localSavePath, FileMode.Create, FileAccess.Write)) {
                    await response.Content.CopyToAsync(fileStream);
                }
            }
        }
    }
}
